#include "MapEditor.h"

#include "NieuwMapDialog.h"
#include "GUILoadMapDialog.h"
#include <QInputDialog>

MapEditor::MapEditor( QWidget* parent )
	: QMainWindow( parent )
{
	// acties
	newAct = new QAction(tr("&Nieuw"), this);
    newAct->setShortcut(tr("Ctrl+N"));
    newAct->setStatusTip(tr("Maak een nieuwe lege map"));
    connect(newAct, SIGNAL(triggered()), this, SLOT(newMap()));

    loadAct = new QAction(tr("&Openen..."), this);
    loadAct->setShortcut(tr("Ctrl+O"));
    loadAct->setStatusTip(tr("Gebruik bestaande map als uitgangspunt"));
    connect(loadAct, SIGNAL(triggered()), this, SLOT(loadMap()));

	saveAct = new QAction(tr("Op&slaan"), this);
    saveAct->setShortcut(tr("Ctrl+S"));
    saveAct->setStatusTip(tr("Gebruik bestaande map als uitgangspunt"));
    connect(saveAct, SIGNAL(triggered()), this, SLOT(saveMap()));

	quitAct = new QAction(tr("A&fsluiten"), this);
    quitAct->setShortcut(tr("Ctrl+Q"));
    quitAct->setStatusTip(tr("Keer terug naar spel"));
    connect(quitAct, SIGNAL(triggered()), this, SLOT(handleQuit()));

    fileMenu = menuBar()->addMenu(tr("&Bestand"));
    fileMenu->addAction(newAct);
    fileMenu->addAction(loadAct);
	fileMenu->addAction(saveAct);
    fileMenu->addSeparator();
	fileMenu->addAction(quitAct);

	saveAct->setEnabled(false);

	this->setMinimumSize(600, 400);

	m_creator = NULL;
} 

void MapEditor::newMap()
{
	NieuwMapDialog nieuw(this);
	if( nieuw.exec() == QDialog::Accepted )
	{
		delete m_creator;
		m_creator = new MapCreator(nieuw.width(),nieuw.height());
    	setCentralWidget(m_creator);
		m_filename = "NieuweMap";
		saveAct->setEnabled(true);
	}

}

#include <iostream>
using namespace std;

void MapEditor::loadMap()
{
	GUILoadMapDialog nieuw(this);
	if( nieuw.exec() == QDialog::Accepted )
	{
		// laden van de map
		Map map;
		map.loadMap(nieuw.getMapId().toStdString());

		delete m_creator;
		m_creator = new MapCreator(map.width(),map.height());
    	setCentralWidget(m_creator);

		for(size_t x = 0; x < map.width(); x++)
			for(size_t y = 0; y < map.height(); y++)
			{
				m_creator->setVakje(x, y, QString(map.getVakje(x, y)->serialize().c_str()) );
			}

		m_filename = map.getNaam().c_str();
		saveAct->setEnabled(true);
	}
}

void MapEditor::saveMap()
{
	 bool ok;
     QString text = QInputDialog::getText(this, tr("Map Opslaan"),
                                          tr("Mapnaam:"), QLineEdit::Normal,
                                         m_filename, &ok);
     if (ok && !text.isEmpty())
     {
		m_filename = text;
		MapParser parser;
		
		m_creator->saveMap( text );
	 }
}

void MapEditor::handleQuit()
{
	emit quit();
}

